<template>
  <div id="cartView">
    <input-search />
    <empty-view
      v-if="cartList.length === 0"
      description="还没有商品加入购物车，快去添加心仪的商品吧！"
    />
    <Waterfall
      :breakpoints="{
        1200: { rowPerView: 2 },
        800: { rowPerView: 1 },
      }"
      :list="cartList"
      style="margin-bottom: 80px"
    >
      <template #default="{ item, _, index }">
        <el-card shadow="hover">
          <div style="padding: 5px; border-radius: 10px; overflow: hidden">
            <el-row style="width: 50%">
              <el-col :span="18">
                <el-checkbox
                  v-model="checkAll[index]"
                  :indeterminate="isIndeterminate[index]"
                  style="font-size: 18px; font-weight: bolder"
                  @change="handleCheckAllChange($event, index)"
                >
                  {{ _ }} {{ item.nickname }}
                </el-checkbox>
              </el-col>
              <el-col :span="6" style="display: flex">
                <el-space>
                  <el-button
                    size="small"
                    type="success"
                    @click="toView('viewBusiness')"
                  >
                    查看店铺
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="toView('chat', item.id)"
                  >
                    联系店家
                  </el-button>
                </el-space>
              </el-col>
            </el-row>
            <el-checkbox-group
              v-model="checked[index]"
              style="width: 100%"
              @change="handleCheckedChange($event, index)"
            >
              <el-row
                v-for="(cart, i) in item.cartInfo"
                :key="cart.id"
                style="margin: 5px 0; width: 100%"
              >
                <el-col :span="1" style="display: flex; align-items: center">
                  <el-checkbox :label="''" :value="cart.id" />
                </el-col>
                <el-col :span="6">
                  <el-image
                    :preview-src-list="[cart.goodsImage || Img]"
                    :src="cart.goodsImage || Img"
                    fit="contain"
                    preview-teleported
                    style="
                      width: 100px;
                      height: 100px;
                      border-radius: 5px;
                      display: block;
                      margin: 0 auto;
                    "
                  />
                </el-col>
                <el-col :span="17" style="padding: 5px">
                  <el-space fill size="small">
                    <el-text
                      :line-clamp="1"
                      class="text-link"
                      size="large"
                      tag="b"
                    >
                      {{ cart.goodsName }}
                    </el-text>
                    <el-text :line-clamp="1" size="small">
                      {{ cart.goodsSpecName }}
                    </el-text>
                    <el-text>
                      <el-space>
                        <el-text
                          v-if="cart.goodsScore < 1"
                          size="small"
                          tag="del"
                          >￥
                          {{ cart.goodsPrice }}
                        </el-text>
                        <el-text size="small" type="danger"
                          >￥
                          <el-text size="large" type="danger"
                            >{{
                              cart.goodsScore < 1
                                ? cart.goodsScopePrice
                                : cart.goodsPrice
                            }}
                          </el-text>
                          到手价
                        </el-text>

                        <el-input-number
                          v-model="cart.goodsNum"
                          :min="0"
                          size="small"
                          @change="handelGoodsNum"
                          @click="selectGoodsNum(index, i)"
                        />
                      </el-space>
                    </el-text>
                  </el-space>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </div>
        </el-card>
      </template>
    </Waterfall>
    <div
      style="
        position: fixed;
        bottom: 0;
        width: 80%;
        background-color: #ffffff;
        z-index: 100;
        border-top: solid 1px #f5f5f5;
      "
    >
      <el-row :gutter="6" style="margin: 0 auto; padding: 10px">
        <el-col :span="4">
          <div style="text-align: left">
            <el-checkbox
              v-model="superCheckAll"
              :indeterminate="superIsIndeterminate"
              @change="handleSuperCheckAllChange"
              >全选
            </el-checkbox>
          </div>
        </el-col>
        <el-col :span="8" style="display: flex">
          <el-space>
            <el-text size="small"
              >已选
              <el-text tag="b"> {{ countData.count }}</el-text>
              件,合计
            </el-text>
            <el-text size="small" type="danger"
              >￥
              <el-text size="large" type="danger"
                >{{ countData.scorePrice }}
              </el-text>
            </el-text>
            <el-text size="small"
              >优惠减：￥ {{ countData.price.sub(countData.scorePrice) }}
            </el-text>
          </el-space>
        </el-col>
        <el-col :span="12">
          <el-row :gutter="12">
            <el-col :span="12">
              <el-button style="width: 100%" type="danger" @click="delCart"
                >移除购物车
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-button style="width: 100%" type="primary" @click="toOrderPay"
                >立即结算
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script lang="ts" setup>
import InputSearch from "@/components/InputSearch.vue";
import { ref, watch } from "vue";
import { Waterfall } from "vue-waterfall-plugin-next";
import "vue-waterfall-plugin-next/dist/style.css";
import {
  CartControllerService,
  CartShowVO,
  OrdersControllerService,
} from "@/api";
import Img from "@/assets/logo.png";
import { useRouter } from "vue-router";
import Decimal from "decimal.js";
import { ElMessage } from "element-plus";
import EmptyView from "@/components/EmptyView.vue";
//选择的基础数据
const basicCheck = ref<Array<number[]>>([]);
// 选中的Id；
const checked = ref<Array<number[]>>([]);
// 是否是半选状态
const isIndeterminate = ref<boolean[]>([]);
//选择所有
const checkAll = ref<boolean[]>([]);

//选择的数据
const init = {
  price: new Decimal(0),
  scorePrice: new Decimal(0),
  count: 0,
};
const countData = ref({
  ...init,
});

function countPrice() {
  //重置数据
  countData.value = {
    ...init,
  };
  for (let i = 0; i < checked.value.length; i++) {
    checked.value[i].forEach((id) => {
      //找到购物车数据
      const cart = cartList.value[i].cartInfo.find((item) => item.id === id);
      //计算乘积
      countData.value.price = countData.value.price.plus(
        new Decimal(cart.goodsPrice).times(cart.goodsNum)
      );

      countData.value.scorePrice = countData.value.scorePrice.plus(
        new Decimal(cart.goodsScopePrice).times(cart.goodsNum)
      );
      countData.value.count = countData.value.count + cart.goodsNum;
    });
  }
}

watch(
  () => checked.value,
  () => {
    //触发计算
    countPrice();
  },
  {
    deep: true,
  }
);

function handleCheckedChange(value: number[], index: any) {
  //选中的值的长度
  const checkedCount = value.length;
  //设置全选状态
  checkAll.value[index] = checkedCount === basicCheck.value[index].length;
  // 设置不确定状态
  isIndeterminate.value[index] =
    checkedCount > 0 && checkedCount < basicCheck.value[index].length;
  //统计全局不确定状态
  superIsIndeterminate.value =
    checkAll.value.filter((item) => item).length < checkAll.value.length;
  //统计全局全选状态
  superCheckAll.value =
    checkAll.value.filter((item) => item).length === checkAll.value.length;
}

//选择所有
const handleCheckAllChange = (val: boolean, index: number) => {
  checked.value[index] = val ? [...basicCheck.value[index]] : [];
  isIndeterminate.value[index] = false;
  //统计全局不确定状态
  superIsIndeterminate.value =
    checkAll.value.filter((item) => item).length < checkAll.value.length;
  //统计全局全选状态
  superCheckAll.value =
    checkAll.value.filter((item) => item).length === checkAll.value.length;
};

const superIsIndeterminate = ref(false);
const superCheckAll = ref(false);

const handleSuperCheckAllChange = (val: boolean) => {
  //全选
  if (val) {
    for (let i = 0; i < checked.value.length; i++) {
      //设置全部原始值
      checked.value[i] = [...basicCheck.value[i]];
      //设置全选状态
      checkAll.value[i] = true;
    }
  } else {
    //清空
    for (let i = 0; i < checked.value.length; i++) {
      checked.value[i] = [];
      checkAll.value[i] = false;
    }
  }
  superIsIndeterminate.value = false;
};

//获取购物车数据
const cartList = ref<CartShowVO[]>([]);

function getCartList() {
  // 重置数据
  basicCheck.value = [];
  checked.value = [];
  isIndeterminate.value = [];
  checkAll.value = [];
  CartControllerService.getCartListUsingGet().then((res) => {
    cartList.value = res.data || [];
    if (cartList.value.length > 0) {
      res.data?.forEach((item) => {
        //获取购物车Id
        const cartIds = item.cartInfo?.map((cart) => cart.id) || [];
        //设置选择的基础数据
        basicCheck.value.push(cartIds as any);
        //初始化基础数据
        checked.value.push([]);
        //设置半选状态
        isIndeterminate.value.push(false);
        // 设置全选状态
        checkAll.value.push(false);
      });
    }
  });
}

getCartList();

const selectCartIndex = ref<number[]>([0, 0]);

function selectGoodsNum(parentIndex: number, index: number) {
  selectCartIndex.value[0] = parentIndex;
  selectCartIndex.value[1] = index;
}

// 数量发送改变
function handelGoodsNum(currentValue: number, oldValue: number) {
  //选择的数据
  const date =
    cartList.value[selectCartIndex.value[0]].cartInfo[selectCartIndex.value[1]];
  date.goodsNum = oldValue;
  CartControllerService.updateCartNumUsingPut({
    id: date.id,
    status: currentValue,
  }).then((res) => {
    ElMessage.success(res.data);
    date.goodsNum = currentValue;
  });
}

//路由跳转
const router = useRouter();

function toView(type: string, id?: number) {
  switch (type) {
    case "view":
    case "chat": {
      router.push({
        path: "/chat",
        query: {
          businessId: id,
        },
      });
    }
  }
}

function delCart() {
  // 获取选择的购物车Id
  const data: number[] = [];
  checked.value.forEach((item) => {
    item.forEach((id) => data.push(id));
  });
  if (data.length === 0) {
    ElMessage.warning("请选择购物车后再删除");
    return;
  }
  CartControllerService.delCartUsingDelete(data).then((res) => {
    ElMessage.success(res.data);
    //刷新数据
    getCartList();
  });
}

//结算购物车
function toOrderPay() {
  // 获取选择的购物车Id
  const data: number[] = [];
  checked.value.forEach((item) => {
    item.forEach((id) => data.push(id));
  });
  if (data.length === 0) {
    ElMessage.warning("请选择购物车后再结算");
    return;
  }
  OrdersControllerService.createOrdersUsingPost(data).then((res) => {
    const ordersNo = res.data;
    //跳转订单结算页
    router.push(`/front/orders_pay/${ordersNo}`);
  });
}
</script>

<style scoped>
#cartView {
  margin-top: 75px;
  position: absolute;
  width: 80%;

  :deep(.el-card__body) {
    padding: 10px;
  }
}

/*关闭复选框组限制*/
:deep(.el-checkbox-group) {
  font-size: 12px;
  line-height: normal;
}
</style>
